package com.zbkj.crmeb.store.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.crmeb.core.common.CommonResult;
import com.crmeb.core.exception.CrmebException;
import com.utils.PriceUtil;
import com.zbkj.crmeb.chant.model.ChannelPicking;
import com.zbkj.crmeb.chant.response.PickingProductResponse;
import com.zbkj.crmeb.chant.service.ChannelPickingService;
import com.zbkj.crmeb.store.model.*;
import com.zbkj.crmeb.store.dao.StoreProductPickingDao;
import com.zbkj.crmeb.store.request.PickingProductRequest;
import com.zbkj.crmeb.store.request.UpdatePickingPriceRequest;
import com.zbkj.crmeb.store.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 批采商品表 服务实现类
 * </p>
 *
 * @author wuzp
 * @since 2022-05-19
 */
@Service
public class StoreProductPickingServiceImpl extends ServiceImpl<StoreProductPickingDao, StoreProductPicking> implements StoreProductPickingService {

    @Autowired
    private ChannelPickingService channelPickingService;
    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    private PriceUtil priceUtil;
    @Autowired
    private StoreOrderInfoService storeOrderInfoService;
    @Autowired
    private StoreOrderInfoPickingService storeOrderInfoPickingService;


    @Override
    public CommonResult<Object> batchUpdatePrice(UpdatePickingPriceRequest request) {
        if(request.getRate().compareTo(BigDecimal.ZERO)<1){
            throw new CrmebException("加价率不能小于等于0");
        }
        boolean update = this.update(Wrappers.<StoreProductPicking>lambdaUpdate()
                .set(StoreProductPicking::getPriceType, 0)
                .set(StoreProductPicking::getPrice, request.getRate())
                .in(StoreProductPicking::getId, request.getIds()));
        return update ? CommonResult.success() : CommonResult.failed();
    }

    @Override
    public CommonResult<Object> updatePickingProduct(PickingProductRequest request) {
        StoreProductPicking storeProductPicking = this.getById(request.getId());
        if(storeProductPicking == null){
            throw new CrmebException("该商品不存在");
        }
        //固定价格最低
        ChannelPicking picking = channelPickingService.getById(storeProductPicking.getPickingId());
        if(picking == null || picking.getIsDel() == 1){
            throw new CrmebException("该批采单不存在");
        }
        StoreProduct storeProduct = storeProductService.getById(storeProductPicking.getProductId());
        //StoreProductAttrValue productAttrValue = storeProductAttrValueService.getById(storeProductPicking.getSkuId());
        StoreProductAttrValue productAttrValue = storeProductAttrValueService.getOne(Wrappers.lambdaQuery(StoreProductAttrValue.class)
                .eq(StoreProductAttrValue::getSourceSkuId,storeProductPicking.getSkuId())
                .eq(StoreProductAttrValue::getProductId,storeProductPicking.getProductId())
                .last("LIMIT 1"));

        PickingProductResponse response = new PickingProductResponse();
        BeanUtils.copyProperties(storeProduct,response);
        response.setCost(productAttrValue.getCost());
        priceUtil.calcPickingProductWholesalePrice(Collections.singletonList(response),picking.getMerId(),picking.getReceiptType());
        //最低售价
        if(request.getPrice().compareTo(response.getCost().add(response.getTaxAndSecondPrice()))<0){
            throw new CrmebException("该商品最低售价:"+response.getCost().add(response.getTaxAndSecondPrice()));
        }
        storeProductPicking.setPriceType(1);
        storeProductPicking.setPrice(request.getPrice());
        return this.updateById(storeProductPicking) ? CommonResult.success() : CommonResult.failed();
    }

    @Override
    public CommonResult<Object> batchDelete(List<Integer> ids) {
        if(CollectionUtils.isEmpty(ids)){
            throw new CrmebException("请输入批采商品id");
        }
        int m = storeOrderInfoService.count(Wrappers.<StoreOrderInfo>lambdaQuery().in(StoreOrderInfo::getPickingProductId, ids));
        if(m > 0){
            throw new CrmebException("存在商品已生成订单!");
        }
        int n = storeOrderInfoPickingService.count(Wrappers.<StoreOrderInfoPicking>lambdaQuery().in(StoreOrderInfoPicking::getPickingProductId, ids));
        if(n > 0){
            throw new CrmebException("存在商品已生成订单!");
        }
        return this.remove(Wrappers.<StoreProductPicking>lambdaQuery().in(StoreProductPicking::getId, ids)) ? CommonResult.success() : CommonResult.failed();
    }

    @Override
    public CommonResult<Object> batchAddPicking(List<Integer> ids, Integer pickingId) {
        if(CollectionUtils.isEmpty(ids)){
            throw new CrmebException("商品id不能为空");
        }
        ChannelPicking channelPicking = channelPickingService.getById(pickingId);
        if(channelPicking == null || channelPicking.getIsDel() == 1){
            throw new CrmebException("该批采单不存在");
        }
        if(channelPicking.getStatementTime().before(new Date())){
            throw new CrmebException("该批采单已结单");
        }
        List<StoreProduct> productList = storeProductService.list(Wrappers.<StoreProduct>lambdaQuery().in(StoreProduct::getId, ids)
                .select(StoreProduct::getId, StoreProduct::getTempId, StoreProduct::getDegree));
        if(productList.stream().anyMatch(e->e.getDegree() != null)){
            throw new CrmebException("二手商品不能加入批采单");
        }
        //发货地判断
        switch (channelPicking.getReceiptType()){
            case 1:
                if(productList.stream().anyMatch(e->e.getTempId() != 1)){
                    throw new CrmebException("该采购单只支持商品发货地是大陆");
                }
                break;
            case 2:
                if(productList.stream().anyMatch(e->e.getTempId() == 1)){
                    throw new CrmebException("该采购单只支持商品发货地是非大陆");
                }
                break;
            default:
                throw new CrmebException("该批采单收货方式异常");
        }
        List<StoreProductAttrValue> productAttrValueList = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery().in(StoreProductAttrValue::getProductId, ids));
        List<String> valueIdList = productAttrValueList.stream().map(StoreProductAttrValue::getSourceSkuId).distinct().collect(Collectors.toList());
        //排除已加入的
        List<StoreProductPicking> productPickingList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(valueIdList)) {
            productPickingList = this.list(Wrappers.<StoreProductPicking>lambdaQuery().eq(StoreProductPicking::getPickingId, pickingId).in(StoreProductPicking::getSkuId, valueIdList).select(StoreProductPicking::getSkuId));
        }
        List<String> exitValueIdList = productPickingList.stream().map(StoreProductPicking::getSkuId).distinct().collect(Collectors.toList());
        List<StoreProductPicking> list = new ArrayList<>();
        for (StoreProductAttrValue value : productAttrValueList) {
            if(exitValueIdList.contains(value.getSourceSkuId())){
                continue;
            }
            StoreProductPicking storeProductPicking = new StoreProductPicking();
            storeProductPicking.setPickingId(pickingId);
            storeProductPicking.setProductId(value.getProductId());
            storeProductPicking.setSkuId(value.getSourceSkuId());
            list.add(storeProductPicking);
        }
        if(CollectionUtils.isNotEmpty(list)){
            return this.saveBatch(list) ? CommonResult.success() : CommonResult.failed();
        }
        return CommonResult.success();
    }

}
